package logic

import (
	"context"
	"errors"
	"tiktok_src/cache"
	"tiktok_src/models/mysql"

	"tiktok_src/internal/svc"
	"tiktok_src/tiktook"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsReleaseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsReleaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsReleaseLogic {
	return &GoodsReleaseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsReleaseLogic) GoodsRelease(in *tiktook.GoodsReleaseRequest) (*tiktook.GoodsReleaseResponse, error) {
	// todo: add your logic here and delete this line
	goods := mysql.Goods{
		UserId:     in.UserId,
		GoodsTitle: in.GoodsTitle,
		GoodsPrice: in.GoodsPrice,
		GoodsStock: in.GoodsStock,
		GoodsCover: in.GoodsCover,
	}
	err := goods.GoodsGetInfo()
	if err != nil {
		logx.Info("商品信息不存在", err)
		return nil, errors.New("商品信息不存在")
	}
	err = goods.Create()
	if err != nil {
		logx.Info("创建商品信息失败", err)
		return nil, errors.New("创建商品信息失败")
	}
	cache.SyncGoods(in.UserId, in.GoodsStock)
	return &tiktook.GoodsReleaseResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
